package com.zl.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.system.comm.util.CheckUtil;
import com.system.comm.util.JsonUtils;
import com.system.comm.util.WechatUtil;
import com.zl.service.ZlLoginService;

@Controller
@RequestMapping("login")
public class wechatLoginController {
	
	@Autowired
	private ZlLoginService zlLoginService;
	
	@RequestMapping("toLogin")
	public String tologin(){
		
		
		return "wechat/login";
	}
	
	@RequestMapping("sendCheckCode")
	public void sendCheckCode(String mobile,HttpSession session,HttpServletResponse response){
		String msgCheck="1234";
		zlLoginService.sendCheckCodeZl(mobile, msgCheck);
		session.setAttribute("msgCheck", msgCheck);
		Map<String, Object> map=new HashMap<>();
		map.put("msg", "1");
		String str=JsonUtils.toJson(map);
		CheckUtil.responseW(response, str);
		
	}
	
	
	
	@RequestMapping("doLogin")
	public void doLogin(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		String state=request.getParameter("loginWay");
		if (state.equals("1")) {
			Map<String, Object> map=zlLoginService.checkCode(request,session);
			String str=JsonUtils.toJson(map);
			CheckUtil.responseW(response, str);
		}else{
			
		}
		
		
	}
	
	
	@RequestMapping(value = "/wxcheck")
	public String check(Model model, HttpServletRequest request, HttpServletResponse response)throws IOException {
	    boolean isGet = request.getMethod().toLowerCase().equals("get");
	    PrintWriter print;
	    if(isGet){
	        // 微信加密签名
	        String signature = request.getParameter("signature");
	        // 时间戳
	        String timestamp = request.getParameter("timestamp");
	        // 随机数
	        String nonce = request.getParameter("nonce");
	        // 随机字符串
	        String echostr = request.getParameter("echostr");
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
	        if (signature != null && WechatUtil.checkSignature(signature, timestamp, nonce)) {
	            try {
	                print = response.getWriter();
	                print.write(echostr);
	                print.flush();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    return "wechat/project/findProject";
	}

	
}
